import { message } from "antd";

// 浏览器检测和兼容性配置
const BROWSER_INFO = {
  isAndroid: /Android/i.test(navigator.userAgent),
  isIOS: /iPhone|iPad|iPod/i.test(navigator.userAgent),
  isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),
  isChrome: /Chrome/i.test(navigator.userAgent),
  isSafari: /Safari/i.test(navigator.userAgent),
  isFirefox: /Firefox/i.test(navigator.userAgent),
  isEdge: /Edg/i.test(navigator.userAgent)
};

class SpeechService {
  // TTS 相关属性
  private synth: SpeechSynthesis;
  private voices: SpeechSynthesisVoice[] = [];
  private currentVoice: SpeechSynthesisVoice | null = null;
  private voicesLoaded: boolean = false;
  private voiceLoadCallbacks: Array<() => void> = [];
  private isSpeaking: boolean = false;
  private currentUtterance: SpeechSynthesisUtterance | null = null;
  
  // 语音识别相关属性
  private recognition: any = null;
  private recognitionType: string = '';
  private isRecognitionSupported: boolean = false;
  
  constructor() {
    // 初始化 TTS
    this.synth = window.speechSynthesis;
    this.initializeTTS();
    
    // 初始化语音识别
    this.initializeSpeechRecognition();
  }
  
  // ========== TTS 功能部分 ==========
  
  // TTS 初始化
  private initializeTTS() {
    if (!this.isTTSSupported()) {
      //console.warn('浏览器不支持 Speech Synthesis API');
      return;
    }
    
    // 移动端需要特殊初始化
    if (BROWSER_INFO.isMobile) {
      this.setupMobileVoiceLoading();
    } else {
      this.loadVoices();
    }
  }
  
  // 设置移动端语音加载策略
  private setupMobileVoiceLoading() {
    // 方法1: 尝试立即加载
    this.voices = this.synth.getVoices();
    if (this.voices.length > 0) {
      this.setDefaultVoice();
      this.voicesLoaded = true;
      this.notifyVoiceCallbacks();
      return;
    }
    
    // 方法2: 监听 voiceschanged 事件
    let voicesChangedFired = false;
    const voicesChangedHandler = () => {
      voicesChangedFired = true;
      this.handleVoicesLoaded();
      this.synth.onvoiceschanged = null;
    };
    
    this.synth.onvoiceschanged = voicesChangedHandler;
    
    // 方法3: 超时后备方案
    setTimeout(() => {
      if (!voicesChangedFired) {
        this.voices = this.synth.getVoices();
        if (this.voices.length > 0) {
          this.handleVoicesLoaded();
        } else {
          //console.log('需要用户交互来加载语音');
        }
      }
    }, BROWSER_INFO.isMobile ? 2000 : 1000);
  }
  
  // 处理语音加载完成
  private handleVoicesLoaded() {
    this.voices = this.synth.getVoices();
    this.setDefaultVoice();
    this.voicesLoaded = true;
    this.notifyVoiceCallbacks();
    
    //console.log(`加载了 ${this.voices.length} 个语音`);
    if (this.voices.length === 0 && BROWSER_INFO.isMobile) {
      //console.warn('移动端语音列表为空，可能需要用户交互');
    }
  }
  
  // 语音加载回调通知
  private notifyVoiceCallbacks() {
    this.voiceLoadCallbacks.forEach(callback => callback());
    this.voiceLoadCallbacks = [];
  }
  
  // 等待语音加载
  private waitForVoices(): Promise<void> {
    return new Promise((resolve) => {
      if (this.voicesLoaded) {
        resolve();
      } else {
        this.voiceLoadCallbacks.push(resolve);
        // 超时保护
        setTimeout(() => {
          const index = this.voiceLoadCallbacks.indexOf(resolve);
          if (index > -1) {
            this.voiceLoadCallbacks.splice(index, 1);
            resolve();
          }
        }, 5000);
      }
    });
  }
  
  // 加载可用语音
  private loadVoices() {
    this.voices = this.synth.getVoices();
    
    if (this.voices.length > 0) {
      this.setDefaultVoice();
      this.voicesLoaded = true;
      this.notifyVoiceCallbacks();
    } else {
      this.synth.onvoiceschanged = () => {
        this.voices = this.synth.getVoices();
        this.setDefaultVoice();
        this.voicesLoaded = true;
        this.notifyVoiceCallbacks();
        this.synth.onvoiceschanged = null;
      };
    }
  }
  
  // 设置默认语音 - 修改为优先英国英文
  private setDefaultVoice() {
    if (BROWSER_INFO.isMobile) {
       //console.log(this.voices)
      const defaultVoice =  this.voices.find(voice => voice.lang.includes('en-GB')) || this.voices.find(voice => voice.default)
      if (defaultVoice) {
      const EnghVoices = this.voices.filter(voice => voice.lang.includes('en-GB'));
      //console.log(EnghVoices)
        this.currentVoice = EnghVoices[3] || defaultVoice; //第二个是男声，第三个是女生
        return;
      }
    }
    
    // 优先英文语音
    const englishVoices = this.voices.filter(voice => 
      voice.lang.includes('en') || voice.lang.includes('US') || voice.lang.includes('GB')
    );
    
    if (englishVoices.length > 0) {
      // 在英文语音中优先选择美式英语
      const usEnglish = englishVoices.find(voice => voice.lang.includes('US')) ||
                       englishVoices.find(voice => voice.lang.includes('en-US'));
      this.currentVoice = usEnglish || englishVoices[0];
      return;
    }
    
    // 其次中文语音
    const chineseVoices = this.voices.filter(voice => 
      voice.lang.includes('zh') || voice.lang.includes('CN')
    );
    
    if (chineseVoices.length > 0) {
      this.currentVoice = chineseVoices[0];
      return;
    }
    
    // 最后选择第一个可用的语音
    this.currentVoice = this.voices.length > 0 ? this.voices[0] : null;
  }
  
  // 优化文本处理 - 解决发音不完整问题
  private processTextForSpeech(text: string): string {
    // 1. 清理文本中的特殊字符和多余空格
    let processedText = text
      .replace(/\s+/g, ' ') // 合并多个空格
      .replace(/[<>]/g, '') // 移除可能干扰的字符
      .trim();
    
    // 2. 确保文本以合适的标点结尾（避免截断）
    if (!/[.!?]$/.test(processedText)) {
      processedText += '.';
    }
    
    // 3. 为移动端优化停顿
    if (BROWSER_INFO.isMobile) {
      // 移动端使用更保守的停顿策略
      processedText = processedText
        .replace(/,/g, ', ')
        .replace(/\./g, '. ')
        .replace(/\?/g, '? ')
        .replace(/!/g, '! ');
    } else {
      // 桌面端使用更自然的停顿
      processedText = processedText
        .replace(/,/g, ', ')
        .replace(/\./g, '. ')
        .replace(/\?/g, '? ')
        .replace(/!/g, '! ')
        .replace(/;/g, '; ');
    }
    
    // 4. 限制文本长度，避免移动端处理长文本出现问题
    if (BROWSER_INFO.isMobile && processedText.length > 200) {
      //console.warn('移动端长文本可能影响语音质量，建议分段处理');
    }
    
    return processedText;
  }
  
  // 移动端语音播放优化 - 增强版本
  private async speakWithMobileOptimization(
    text: string, 
    utterance: SpeechSynthesisUtterance
  ): Promise<boolean> {
    
    return new Promise((resolve) => {
      let hasStarted = false;
      let hasEnded = false;
      let startTimer: NodeJS.Timeout;
      let endTimer: NodeJS.Timeout;
      
      const startHandler = () => {
        //console.log('语音开始播放');
        hasStarted = true;
        clearTimeout(startTimer);
      };
      
      const endHandler = () => {
        //console.log('语音播放完成');
        hasEnded = true;
        this.isSpeaking = false;
        this.currentUtterance = null;
        cleanup();
        resolve(true);
      };
      
      const errorHandler = (event: SpeechSynthesisErrorEvent) => {
        //console.error('移动端语音合成错误:', event.error);
        this.isSpeaking = false;
        this.currentUtterance = null;
        cleanup();
        resolve(false);
      };
      
      const cleanup = () => {
        utterance.onstart = null;
        utterance.onend = null;
        utterance.onerror = null;
        clearTimeout(startTimer);
        clearTimeout(endTimer);
      };
      
      utterance.onstart = startHandler;
      utterance.onend = endHandler;
      utterance.onerror = errorHandler;
      
      // 尝试播放
      try {
        this.synth.speak(utterance);
        
        // 移动端启动超时检测
        startTimer = setTimeout(() => {
          if (!hasStarted) {
            //console.warn('移动端语音启动超时，尝试重新播放');
            cleanup();
            resolve(false);
          }
        }, 3000);
        
        // 播放完成超时保护（防止无限等待）
        endTimer = setTimeout(() => {
          if (!hasEnded) {
            //console.warn('语音播放超时，强制结束');
            this.isSpeaking = false;
            this.currentUtterance = null;
            cleanup();
            resolve(false);
          }
        }, 60000); // 60秒超时
      } catch (error) {
        //console.error('播放异常:', error);
        cleanup();
        resolve(false);
      }
    });
  }
  
  // 设置语音
  async setVoice(voiceName: string) {
    await this.waitForVoices();
    
    const voice = this.voices.find(v => v.name === voiceName);
    if (voice) {
      this.currentVoice = voice;
      return true;
    } else {
      //console.warn(`未找到名为 ${voiceName} 的语音`);
      return false;
    }
  }
  
  // 获取所有可用语音
  async getAvailableVoices(): Promise<SpeechSynthesisVoice[]> {
    await this.waitForVoices();
    return this.voices;
  }
  
  // 获取当前语音
  async getCurrentVoice(): Promise<SpeechSynthesisVoice | null> {
    await this.waitForVoices();
    return this.currentVoice;
  }
  
  // 朗读文本 - 优化版本
  async speak(text: string, options: {
    rate?: number, 
    pitch?: number, 
    volume?: number,
    onStart?: () => void,
    onEnd?: () => void,
    onError?: (error: string) => void
  } = {}): Promise<boolean> {
    
    if (!this.isTTSSupported()) {
      const errorMsg = '您的浏览器不支持语音合成功能,请更换其他浏览器尝试';
      options.onError?.(errorMsg);
      //message.error(errorMsg);
      return false;
    }
    
    // 等待语音加载完成
    await this.waitForVoices();
    
    // 如果正在播放，先停止（但增加延迟确保完全停止）
    if (this.isSpeaking && this.synth.speaking) {
      this.synth.cancel();
      // 增加停止后的延迟，确保资源释放
      await new Promise(resolve => setTimeout(resolve, 200));
    }
    
    // 优化文本处理
    const processedText = this.processTextForSpeech(text);
    //console.log('处理后的文本:', processedText);
    
    try {
      const utterance = new SpeechSynthesisUtterance(processedText);
      this.currentUtterance = utterance;
      this.isSpeaking = true;
      
      // 语音设置 - 优化参数
      utterance.voice = this.currentVoice;
      
      // 调整语速：移动端稍慢，桌面端正常
      utterance.rate = BROWSER_INFO.isMobile ? 
        Math.min(options.rate || 0.85, 1.0) : // 移动端最大不超过1.0
        (options.rate || 1.0);
      
      utterance.pitch = options.pitch || 1.0;
      utterance.volume = Math.min(options.volume || 1.0, 1.0); // 确保不超过1.0
      
      // 事件处理 - 增强错误处理
      utterance.onstart = () => {
        //console.log('语音合成开始');
        this.isSpeaking = true;
        options.onStart?.();
      };
      
      utterance.onend = () => {
        //console.log('语音合成正常结束');
        this.isSpeaking = false;
        this.currentUtterance = null;
        options.onEnd?.();
      };
      
      utterance.onerror = (event) => {
        //console.error('语音合成错误:', event.error);
        this.isSpeaking = false;
        this.currentUtterance = null;
        const errorMsg = `语音合成错误: ${event.error}`;
        options.onError?.(errorMsg);
      };
      
      // 边界事件处理（部分浏览器支持）
      utterance.onboundary = (event) => {
        //console.log('语音边界事件:', event);
      };
      
      // 根据设备类型采用不同的播放策略
      if (BROWSER_INFO.isMobile) {
        return await this.speakWithMobileOptimization(text, utterance);
      } else {
        this.synth.speak(utterance);
        return true;
      }
      
    } catch (error) {
      //console.error('语音朗读失败', error);
      this.isSpeaking = false;
      this.currentUtterance = null;
      options.onError?.(error instanceof Error ? error.message : '未知错误');
      return false;
    }
  }
  
  // 停止朗读 - 优化版本
  stopTTS() {
    if (this.synth.speaking || this.isSpeaking) {
      //console.log('停止语音播放');
      this.synth.cancel();
      this.isSpeaking = false;
      this.currentUtterance = null;
      
      // 强制清理语音合成队列
      try {
        // 尝试彻底停止所有语音活动
        if (this.synth.paused) {
          this.synth.resume(); // 先恢复再取消
        }
        this.synth.cancel();
      } catch (error) {
        //console.warn('停止语音时出现小问题:', error);
      }
    }else{
      return
    }
  }
  
  // 暂停朗读
  pauseTTS() {
    if (this.synth.speaking && !this.synth.paused) {
      this.synth.pause();
    }
  }
  
  // 继续朗读
  resumeTTS() {
    if (this.synth.speaking && this.synth.paused) {
      this.synth.resume();
    }
  }
  
  // 检查是否正在播放
  isSpeakingNow(): boolean {
    return this.isSpeaking;
  }
  
  // 检查TTS是否支持
  isTTSSupported(): boolean {
    return typeof window !== 'undefined' && 'speechSynthesis' in window;
  }
  
  // 预加载语音
  async preloadVoices(): Promise<boolean> {
    if (this.voicesLoaded) return true;
    
    // 在移动端，尝试通过创建一个无声的 utterance 来触发语音加载
    if (BROWSER_INFO.isMobile && this.voices.length === 0) {
      const tempUtterance = new SpeechSynthesisUtterance('');
      tempUtterance.volume = 0;
      this.synth.speak(tempUtterance);
      this.synth.cancel();
    }
    
    return this.waitForVoices().then(() => true);
  }

  // ========== 语音识别功能部分 ==========
  
  // 初始化语音识别
  private initializeSpeechRecognition() {
    this.setRecognitionType();
    
    if (this.isRecognitionSupported) {
      this.createRecognitionInstance();
    } else {
      //console.warn('当前浏览器不支持语音识别功能');
    }
  }
  
  // 检测和设置语音识别API类型
  private setRecognitionType(): void {
    // 检测浏览器支持的语音识别API类型
    if (window.SpeechRecognition) {
      this.recognitionType = 'standard';
      this.isRecognitionSupported = true;
    } else if (window.webkitSpeechRecognition) {
      this.recognitionType = 'webkit';
      this.isRecognitionSupported = true;
    } else {
      this.recognitionType = 'unsupported';
      this.isRecognitionSupported = false;
    }
    
    //console.log(`语音识别API类型: ${this.recognitionType}`);
  }
  
  // 创建语音识别实例
  private createRecognitionInstance(): void {
    const RecognitionClass = window.SpeechRecognition || window.webkitSpeechRecognition;
    
    if (!RecognitionClass) {
      this.isRecognitionSupported = false;
      return;
    }
    
    this.recognition = new RecognitionClass();
    
    // 根据API类型进行不同配置
    if (this.recognitionType === 'standard') {
      // 标准API配置
      this.recognition.continuous = false;
      this.recognition.interimResults = true;
      this.recognition.lang = 'en-US'; // 默认改为英文
    } else {
      // Webkit API配置
      this.recognition.continuous = false;
      this.recognition.interimResults = true;
      this.recognition.lang = 'en-US'; // 默认改为英文
    }
    
    // 设置最大备选结果数量
    this.recognition.maxAlternatives = 1;
  }
  
  // 开始语音识别
  startRecognition(options: {
    onResult?: (text: string, isFinal: boolean) => void;
    onStart?: () => void;
    onEnd?: () => void;
    onError?: (error: string) => void;
    lang?: string;
    continuous?: boolean;
  } = {}): boolean {
    
    if (!this.isRecognitionSupported || !this.recognition) {
      const errorMsg = '语音识别不被支持或未初始化';
      options.onError?.(errorMsg);
      return false;
    }
    
    try {
      // 配置识别参数
      if (options.lang) {
        this.recognition.lang = options.lang;
      } else {
        // 如果没有指定语言，默认使用英文
        this.recognition.lang = 'en-US';
      }
      
      if (options.continuous !== undefined) {
        this.recognition.continuous = options.continuous;
      }
      
      // 设置事件处理器
      this.recognition.onresult = (event: any) => {
        let finalTranscript = '';
        let interimTranscript = '';
        
        for (let i = event.resultIndex; i < event.results.length; i++) {
          const transcript = event.results[i][0].transcript;
          if (event.results[i].isFinal) {
            finalTranscript += transcript;
          } else {
            interimTranscript += transcript;
          }
        }
        
        if (options.onResult) {
          if (finalTranscript) {
            options.onResult(finalTranscript, true);
          } else if (interimTranscript) {
            options.onResult(interimTranscript, false);
          }
        }
      };
      
      this.recognition.onstart = () => {
        options.onStart?.();
      };
      
      this.recognition.onend = () => {
        options.onEnd?.();
      };
      
      this.recognition.onerror = (event: any) => {
        const errorMap: { [key: string]: string } = {
          'no-speech': '未检测到语音',
          'audio-capture': '无法捕获音频',
          'not-allowed': '语音识别被拒绝',
          'network': '网络错误',
          'aborted': '语音识别被中止'
        };
        
        const errorMsg = errorMap[event.error] || `识别错误: ${event.error}`;
        options.onError?.(errorMsg);
      };
      
      // 开始识别
      this.recognition.start();
      return true;
      
    } catch (error) {
      //console.error('启动语音识别失败:', error);
      options.onError?.(error instanceof Error ? error.message : '未知错误');
      return false;
    }
  }
  
  // 停止语音识别
  stopRecognition(): void {
    if (this.recognition) {
      this.recognition.stop();
    }
  }
  
  // 检查语音识别是否支持
  // isRecognitionSupported(): boolean {
  //   return this.isRecognitionSupported;
  // }
  
  // 获取语音识别API类型
  getRecognitionType(): string {
    return this.recognitionType;
  }
  
  // 设置识别语言
  setRecognitionLanguage(lang: string): boolean {
    if (!this.recognition) {
      return false;
    }
    
    try {
      this.recognition.lang = lang;
      return true;
    } catch (error) {
      //console.error('设置识别语言失败:', error);
      return false;
    }
  }
  
  // ========== 工具方法 ==========
  
  // 获取浏览器信息
  getBrowserInfo() {
    return BROWSER_INFO;
  }
  
  // 检查整体语音支持情况
  getSpeechSupportInfo() {
    return {
      ttsSupported: this.isTTSSupported(),
      recognitionSupported: this.isRecognitionSupported,
      recognitionType: this.recognitionType,
      browserInfo: BROWSER_INFO
    };
  }
  
  // 获取当前语音语言信息
  getCurrentVoiceLanguage(): string {
    return this.currentVoice ? this.currentVoice.lang : '未知';
  }
  
  // 分段朗读长文本（解决长文本截断问题）
  async speakChunkedText(fullText: string, chunkSize: number = 100, options: {
    rate?: number, 
    pitch?: number, 
    volume?: number,
    onStart?: () => void,
    onEnd?: () => void,
    onError?: (error: string) => void,
    onChunkStart?: (chunk: string, index: number) => void,
    onChunkEnd?: (chunk: string, index: number) => void
  } = {}): Promise<boolean> {
    
    // 将长文本分割成小块
    const sentences = fullText.split(/(?<=[.!?])\s+/);
    let chunks: string[] = [];
    
    // 按句子组合，确保每个块不超过chunkSize
    let currentChunk = '';
    for (const sentence of sentences) {
      if ((currentChunk + sentence).length <= chunkSize) {
        currentChunk += (currentChunk ? ' ' : '') + sentence;
      } else {
        if (currentChunk) chunks.push(currentChunk);
        currentChunk = sentence;
      }
    }
    if (currentChunk) chunks.push(currentChunk);
    
    //console.log(`将文本分割为 ${chunks.length} 个块`);
    
    // 逐块播放
    for (let i = 0; i < chunks.length; i++) {
      const chunk = chunks[i];
      options.onChunkStart?.(chunk, i);
      
      const success = await this.speak(chunk, {
        rate: options.rate,
        pitch: options.pitch,
        volume: options.volume,
        onStart: i === 0 ? options.onStart : undefined,
        onEnd: i === chunks.length - 1 ? options.onEnd : undefined,
        onError: options.onError
      });
      
      options.onChunkEnd?.(chunk, i);
      
      if (!success) {
        return false;
      }
      
      // 在块之间添加短暂停顿（除了最后一块）
      if (i < chunks.length - 1) {
        await new Promise(resolve => setTimeout(resolve, 300));
      }
    }
    
    return true;
  }
}

// 创建单例实例
const speechService = new SpeechService();
export default speechService;